/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.CreditinvestigationDAO;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Creditinvestigations;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Usertypes;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Dine
 */
public class GridCreditinvestigation extends ActionSupport {

    private static Logger logger = Logger.getLogger(GridCreditinvestigation.class);
    //Your result List
    private List<Creditinvestigations> gridModel;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 0;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
    // get index row - i.e. user click to sort.
    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    // All Record
    private Integer records = 0;
    private CreditinvestigationDAO crdao = (CreditinvestigationDAO) ServletActionContext.getServletContext().getAttribute("creditinvestigationDAO");
    private Usertypes ut = (Usertypes) ServletActionContext.getRequest().getSession().getAttribute("usertype");

    @Action(value = "/grid-creditinv", results = {
        @Result(name = "success", type = "json"),
        @Result(name = "error", location = "../error/messages.jsp")
    })
    @Override
    public String execute() {
        try {
            //max record
            int to = (rows * page);
            //offset record
            int from = to - rows;

            DetachedCriteria criteria = criteria = DetachedCriteria.forClass(Creditinvestigations.class);
            criteria.createCriteria("employees", "e").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            criteria.createCriteria("documents", "d").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            criteria.createCriteria("loanapplications").createCriteria("documents", "ld").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
           

            //set criteria search restrictions
            if (searchField != null && searchField.length() > 0) {
                if (searchField.equals("idnumber")) {
                    criteria.add(Restrictions.like("e.idnumber", "%" + searchString + "%"));
                } else if (searchField.equals("documentno")) {
                    criteria.add(Restrictions.like("d.documentno", "%" + searchString + "%"));
                } else if (searchField.equals("loanappdocumentno")) {
                    criteria.add(Restrictions.like("ld.documentno", "%" + searchString + "%"));
                } else {
                    criteria.add(Restrictions.like(searchField,searchString));
                }
            }
            
            //Handle branch and usertype session
            // 1 = President, 13 = Adminstrator
            logger.info("type: " + ut.getUsertypeid());
            if (ut.getUsertypeid() != 1 && ut.getUsertypeid() != 13) {
                //GET THE BRANCH SET UPON LOGIN in LINE 71 in LoginAuthentication.java
                Branches branch = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
                logger.info("branch: " + branch.getBranchcode());
                if (branch.getBranchcode().equals("HO")) {//if Head Office..
                    //Set grid to show only loanapps in that branch 
                    //This code is equivalent to "from Loanapplications l inner join l.branches b where b.branchcode=:branchcode"
                    //If you look at line 69 - 79 of this file you can see that I joined the foreign keyed tables already...

                    criteria.add(Restrictions.eq("stat", "pending"));
                } else {
//                    criteria.createCriteria("loanapplications").createCriteria("branches", "b").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
//                    criteria.add(Restrictions.eq("b.branchcode", branch.getBranchcode()));
                    criteria.add(Restrictions.eq("stat", "saved"));
                }
            }

            // count employees
            records = crdao.countByCriteria(criteria);

            // reset count Projection, note: projection when incremented will set entry point for database,
            // so we need to reset it after counting all records.
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.ROOT_ENTITY);

            // handle Order By
            if (sidx != null && !sidx.equals("")) {

                if (sidx.equals("idnumber")) {
                    sidx = "e.idnumber";
                } else if (sidx.equals("documentno")) {
                    sidx = "d.documentno";
                } else if (sidx.equals("loanappdocumentno")) {
                    sidx = "ld.documentno";
                }

                if (sord.equals("asc")) {
                    criteria.addOrder(Order.asc(sidx));
                } else {
                    criteria.addOrder(Order.desc(sidx));
                }

            }

            //et to = max rows
            if (to > records) {
                to = records;
            }

            // get all employees by criteria
            gridModel = crdao.findByCriteria(criteria, from, to);

            //total pages
            total = (int) Math.ceil((double) records / (double) rows);
        } catch (Exception e) {
            //catch whichever exception, get the current session info of the employee and log it.
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
            } else {
                logger.fatal(e.getLocalizedMessage(), e);
                e.printStackTrace();
            }

            //add action errors this will correspond to <s:actionerror/> in a struts-enabled jsp page.
            addActionError(e.getLocalizedMessage());

            //if error then chain result to messages.jsp, which will display errors/messages.
            return ERROR;
        }
        return SUCCESS;
    }

    public String getJSON() {
        return execute();
    }

    public List<Creditinvestigations> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<Creditinvestigations> gridModel) {
        this.gridModel = gridModel;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}
